// import PubSub from 'pubsub-js';
import request from "../../../../utils/request";
const DB = wx.cloud.database()
const collectDB = DB.collection('collect')
// 获取全局实例
const appInstance = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        listId:'',          //歌单id
        ids:'',             //id列表
        playlist:[],        //歌单详情列表
        index:'',
        t:2,                //记录收藏情况
        type:'',             //通信id
        globList:[],         //全局播放列表
        commentTabs:['推荐',"最热","最新"],
        songlist:[],         //歌单音乐列表
        sortType:1,       //评论类型
        pageNo:1,
        TabCur:0,
        cursor:0,
        comments:[],
        inputContent: '',
        
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        //初始化歌单列表id
       let {listId} = this.data
       listId = options.listid
       let songer = false
       if(options.type){songer=true}
       this.setData({
        listId,
        songer
       })
       this.getDetail()         //获取歌单详情与id列表
       this.DBstatus()

       this.getconnment(listId)
    },
    DBstatus(){
      // console.log("shujuku")
      let listId = this.data.listId/1
      // console.log(typeof listId)
      let that = this
      const _ = DB.command
      // console.log(_)
        collectDB.where(_.and([
          {
            userId: appInstance.globalData.userId
          },
          {
            songlists: {
              id: listId
            }
          }
        ]))
        .get({
          success: function(res) {
            // console.log(res.data)
            if(res.data.length !==0 ){
              // console.log(res.data)
              that.setData({
                shoucan:true
              })
            }
          }
        })
    },
    showModal(e) {
      // console.log(e.currentTarget.dataset)
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    },
    hideModal(e) {
      this.setData({
        modalName: null
      })
    },
      // 点击切换评论类型
  tabSelect(e) {
    let {sortType,listId} = this.data
    if(this.data.TabCur == e.currentTarget.dataset.id){
      return 
    }else{
      sortType=e.currentTarget.dataset.id+1
      let cursor = 0
      this.setData({
        sortType,
        pageNo:1,
        cursor,
        comments:[],
        TabCur: e.currentTarget.dataset.id,
        scrollLeft: (e.currentTarget.dataset.id-1)*60
      })
    }
    this.getconnment(listId)
  },
    // 获取歌单评论
    async getconnment(listId){
      let {comments,sortType,pageNo,cursor} = this.data
      let id = listId
      let pageSize = 40
      if(sortType==1){
         pageSize = 200
      }
      console.log(id,"+",sortType,"+",pageNo)
      let res = await request("/comment/new",{type:2,id,pageSize,sortType,pageNo,cursor})
      if(res.code==200&&res.comments!==[]){
        console.log(res)
        pageNo++
        comments.push(...res.data.comments)
        // console.log(res.data.cursor/1)
      
        this.setData({
          comments,
          cursor:res.data.cursor/1,
          pageNo
        })
      }

  },
// 评论点赞
async dianzan2(event){
  let dataset = event.currentTarget.dataset
  let commtype = dataset.commtype
  if(commtype==='comments'){
    let {comments} = this.data
    let liked = comments.liked
    let t = ''
    if(comments[dataset.cindex].t){
      t = (comments[dataset.cindex].t==1)?0:1
    }else{
       t = comments[dataset.cindex].liked?0:1
    }
    let res = await request("/comment/like",{id:this.data.musicId,type:0,cid:dataset.cid,t})
    if(res.code=200){
      if(t==1){
        comments[dataset.cindex].likedCount++
      }else{
        comments[dataset.cindex].likedCount--
      }
      comments[dataset.cindex].liked=(t==1)?true:false
      comments[dataset.cindex].t = t
      this.setData({
        comments
      })
    }else if(res.code==301){
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        success: () => {
          // 跳转至登录界面
          wx.navigateTo({
            url: '/pages/login/login'
          })
        }
      })
    }
  }else{
    let {comments} = this.data
    let liked = comments.liked
    let t = ''
    if(comments[dataset.cindex].t){
      t = (comments[dataset.cindex].t==1)?0:1
    }else{
       t = comments[dataset.cindex].liked?0:1
    }
    let res = await request("/comment/like",{id:this.data.musicId,type:0,cid:dataset.cid,t})
    if(res.code=200){
      if(t==1){
        comments[dataset.cindex].likedCount++
      }else{
        comments[dataset.cindex].likedCount--
      }
      comments[dataset.cindex].liked=(t==1)?true:false
      comments[dataset.cindex].t = t
      this.setData({
        comments
      })
    }else if(res.code==301){
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        success: () => {
          // 跳转至登录界面
          wx.navigateTo({
            url: '/pages/login/login'
          })
        }
      })
    }
  }

},
chudi(){
  let {listId} = this.data
  // console.log(TabCur)
  this.getconnment(listId)
},
  //发送评论
  async sendcomment(){
    
    let {inputContent,listId} = this.data
    let res = await request("/comment",{id:listId,content:inputContent,t:1,type:2})
    
    if(res.code == 200){
      wx.showToast({
        title: '上传成功!',
        duration: 1000,
        icon:"success",
        success:()=>{
        }
      })
      this.setData({
        inputContent:''
      })
    }
  },
  handleInputChange(e) {
    this.setData({
      inputContent:e.detail.value
    })
  },


    //获取歌手详情
    async getsongerdetail(id){
      
      let res = await request('/artist/detail',{id})
      console.log(res)
      this.setData({
        songerDetail:res
      })
    },
    //获取歌单的id列表
    async getDetail(){
        let {listId} = this.data
        let idList = []
        let url = ''
        if(this.data.songer==true){
          this.getsongerdetail(listId)
          url = "/artist/songs"

        }else{
          url = '/playlist/detail'
        }
        let res = await request(url,{id:listId,order:"hot"})
        // console.log(res)
        let  playlist = res.playlist?res.playlist:res.songs
        let  trackIds = playlist.trackIds          //id列表详情
        if(!trackIds){
          trackIds = playlist.forEach((item,index)=>{
            let id = ''
            id = item.id
            idList.push(id)
          })
        }else{
          trackIds.forEach((item,index) => {
            let id = ''
            id = item.id
            idList.push(id)
        });
        }

        let playcount = Math.floor(playlist.playCount/10000)
        let commentCount = playlist.commentCount
        if(playcount>100000){
          playcount = "9999+"
        }
        if( commentCount>100000 ){
          commentCount = '99999+'
        }
        // console.log(playcount)
        playlist.playCount = playcount
        playlist.commentCount = commentCount
        let ids = idList.toString()             //将id列表转为字符串
        // console.log(idList)
        // console.log(ids)
        this.setData({
            playlist,
            ids
        })
        this.getIdList()         //获取歌单的音乐的列表

    },


    //获取歌单的音乐的列表
    async getIdList(){
        let {ids} = this.data
        let res = await request('/song/detail', {ids: ids});
        let songlist = res.songs
        // console.log(songlist)
        this.setData({
          songlist
        })
    },


  // 跳转至songDetail页面
  toSongDetail(event){
    let {listId} = this.data
    let that = this;
    let globList=[];
    let index
    // if(event.currentTarget.dataset.index){
    //    index = event.currentTarget.dataset.index;
    // }else{
    //   index = 0
    // }
    index = event.currentTarget.dataset.index;
    let {songlist} =this.data
    this.setData({
      index,
      type:`playList`
    })
    //  console.log(this.data.type)
    songlist.forEach((item,index) => {
        let obj = {}
        obj.name = item.name;
        obj.artists= item.ar;
        obj.id = item.id
        globList.push(obj)
      });
      // console.log(globList)
  
      this.setData({
        globList
      })
  
      
      appInstance.globalData.playList = that.data.globList;
      appInstance.globalData.currentIndex = index;
      console.log(index)
      // console.log(songlist[index].id)
    // 路由跳转传参： query参数
    wx.navigateTo({
      // 不能直接将song对象作为参数传递，长度过长，会被自动截取掉
      // url: '/pages/songDetail/songDetail?songPackage=' + JSON.stringify(songPackage)
      url: `/pages/songPackage/pages/playmusic/playmusic?type=${this.data.type}&musicId=` + songlist[index].id,
      // success:function(){

      // }
    },

    )
  },

    // playall(){

    // },

      SouChan(){
        // console.log("shujuku")
        let listId = this.data.listId/1
        let {shoucan} = this.data
        let {playlist} = this.data
        let inserlist = {
          id:playlist.id,
          name:playlist.name,
          url:playlist.coverImgUrl
        }
        let that = this
        const _ = DB.command
        if(!shoucan){
         //  console.log("userid:",appInstance.globalData.userId)
          collectDB.where({userId:appInstance.globalData.userId}).get({
           success(res){
             // console.log("查询成功：",res)
             if(res.data.length === 0){  
               // console.log(res.data.length)
               console.log("用户不存在")
             }else{
               // console.log(appInstance.globalData.userId)
               console.log("用户存在")
               // console.log(_)
               // console.log(collectDB.doc(appInstance.globalData.userId))
               collectDB.where({userId:appInstance.globalData.userId}).update({
                 data:{
                   songlists: _.unshift(inserlist)
                 },
                 success: function(res) {
                   // console.log(inserlist)
                   if(res.stats.updated===1){
                     console.log("添加成功：",res)
                     that.setData({
                       shoucan:true
                     })
                   }
                 },
                 false(err){
                   console.log("添加失败",err)
                 }
               })
               
             }
            
           }
         })
        }else{
            console.log("取消收藏")
            collectDB.where({userId:appInstance.globalData.userId}).get({
              success(res){
                // console.log("查询成功：",res)
                if(res.data.length === 0){  
                  // console.log(res.data.length)
                  console.log("用户不存在")
                }else{
                  // console.log(appInstance.globalData.userId)
                  console.log("用户存在")
                  // console.log(_)
                  // console.log(collectDB.doc(appInstance.globalData.userId))
                  collectDB.where({userId:appInstance.globalData.userId}).update({
                    data:{
                      songlists: _.pull(inserlist)
                    },
                    success: function(res) {
                      // console.log(inserlist)
                      if(res.stats.updated===1){
                        console.log("添加成功：",res)
                        that.setData({
                          shoucan:false
                        })
                      }
                    },
                    false(err){
                      console.log("添加失败",err)
                    }
                  })
                  
                }
               
              }
            })
        }


     
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
      
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})